﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Threading.Tasks;
using NHibernate.Linq;

namespace Data.Impl
{
    public class GenericRepository : IGenericRepository
    {
        [Dependency]
        public SessionManager SessionManager { private get; set; }

        public void Save<T>(T entity)
            where T : class
        {
            var sess = SessionManager.GetSession();
            sess.SaveOrUpdate(entity);
            sess.Flush();
        }

        public void SaveRange<T>(IEnumerable<T> entities) where T : class
        {
            var sess = SessionManager.GetSession();
            foreach (var e in entities) sess.SaveOrUpdate(e);
            sess.Flush();
        }

        public T[] GetAll<T>()
             where T : class
        {
            var sess = SessionManager.GetSession();
            return sess.Query<T>().ToArray();
        }


        public T GetById<T>(object id) where T : class
        {
            var sess = SessionManager.GetSession();
            return sess.Get<T>(id);
        }


        public IQueryable<T> GetQueryable<T>() where T : class
        {
            var sess = SessionManager.GetSession();
            return sess.Query<T>();
        }


        public void Delete<T>(T entity) where T : class
        {
            var sess = SessionManager.GetSession();
            sess.Delete(entity);
            sess.Flush();
        }
    }
}
